import $V from './$V';
import ema from './ema';

export default function cci(high, low, close, length = 14) {
    let md = $V.init(high.length, 0.0001);
    let tp = $V.div_constant($V.add($V.add(high, low), close), 3);
    let matp = ema(tp, length);
    for (let i = length; i < high.length; i++) {
        md[i] = $V.sum($V.abs($V.sub($V.subv(tp, i - length, i), $V.init(length, matp[i])))) / length;
    }
    let result = $V.div($V.sub(tp, matp), $V.mul_constant(md, 0.015));
    result = $V.set_by_index(result, $V.where(result, '==', 'NaN'), 0);
    result = $V.set_by_index(result, $V.where(result, '==', Infinity), 0);
    result = $V.set_by_index(result, $V.where(result, '>', 200), 200);
    result = $V.set_by_index(result, $V.where(result, '<', -200), -200);
    return result;
}
